﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace OverStore
{
    /// <summary>
    /// Caches sequence returned by an enumerator and allows lazy loading of enumerator sequence.
    /// </summary>
    /// <typeparam name="T">Type of element in sequence.</typeparam>
	/// <remarks>
	/// How does stuff work?
	/// The main idea of the CacheEnumerable is to iterate source sequence only once, 
	/// and to cache results to internal storage - for example, in List.
	/// 
	/// Internal storage is filled up while source enumerator is advanced.
	/// New enumerators opened using the instance starts iteration using internal storage.
	/// When it reaches storage end, it checks does source enumerator contain more elements, and if it does,
	/// continue iteration throught source enumerator, and by the way adds elements to storage.
	/// 
	/// Once source enumerator reaches its end, it must be disposed and free.
	/// </remarks>
    public class CacheEnumerable<T> : IEnumerable<T>, IDisposable
    {
        private IEnumerable<T> _SourceEnumerable;

		private IEnumerator<T> _SourceEnumerator;
		private bool _SourceEnumeratorFullyFetched;
		private bool _Disposed;

        private readonly List<T> _Cache = new List<T>();

        /// <summary>
        /// Initializes a new instance of the <see cref="CacheEnumerable&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="sourceEnumerable">The source enumerable.</param>
        public CacheEnumerable(IEnumerable<T> sourceEnumerable)
        {
            if (Object.ReferenceEquals(sourceEnumerable, null))
                throw new ArgumentNullException("sourceEnumerable");
            _SourceEnumerable = sourceEnumerable;
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<T> GetEnumerator()
        {
			if (_Disposed)
				throw new ObjectDisposedException(ToString());
			if (_SourceEnumeratorFullyFetched)
				return _Cache.GetEnumerator();
            return new CacheEnumerator(this);
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

		/// <summary>
		/// Cache Enumerator uses indexed access to parent enumerable cache to prevent 
		/// enumeration failing while changing cache content.
		/// </summary>
        private class CacheEnumerator : IEnumerator<T>
        {
            private readonly CacheEnumerable<T> _Enumerable;
            private int _CacheIndex = -1;

            public CacheEnumerator(CacheEnumerable<T> cacheEnumerable)
            {
                _Enumerable = cacheEnumerable;
            }

            public T Current
            {
                get
                {
                    if (_CacheIndex == -1)
                        throw new InvalidOperationException("The enumerator is positioned before the first element.");
                    if (_CacheIndex < _Enumerable._Cache.Count)
                        return _Enumerable._Cache[_CacheIndex];
                    else
                        throw new InvalidOperationException("The enumerator is positioned after the last element.");
                }
            }

            object System.Collections.IEnumerator.Current { get { return Current; } }

            public void Dispose()
            {
            }

            public bool MoveNext()
            {
            	_CacheIndex++;
            	if (_CacheIndex < _Enumerable._Cache.Count)
            		return true;
            	if (_Enumerable._SourceEnumeratorFullyFetched)
            		return false;

            	if (_Enumerable._SourceEnumerator == null)
            		_Enumerable._SourceEnumerator = _Enumerable._SourceEnumerable.GetEnumerator();
            	var result = _Enumerable._SourceEnumerator.MoveNext();
            	if (!result)
            	{
            		_Enumerable._SourceEnumerator.Dispose();
            		_Enumerable._SourceEnumerator = null;
            		if (_Enumerable._SourceEnumerable is IDisposable)
            			(_Enumerable._SourceEnumerable as IDisposable).Dispose();
            		_Enumerable._SourceEnumerable = null;
            		_Enumerable._SourceEnumeratorFullyFetched = true;
            		return false;
            	}
            	
				_Enumerable._Cache.Add(_Enumerable._SourceEnumerator.Current);
            	return true;
            }

			public void Reset()
            {
                _CacheIndex = -1;
            }
        }

		/// <summary>
		/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
		/// </summary>
		public void Dispose() 
		{
			if (_Disposed)
				return;
			_Disposed = true;
			if (_SourceEnumerator != null)
				_SourceEnumerator.Dispose();
			var e = _SourceEnumerable as IDisposable;
			if (e != null)
				e.Dispose();
			_SourceEnumerator = null;
			_SourceEnumerable = null;
		}
	}

    /// <summary>
    /// Exposes set of static methods allows using of <see cref="CacheEnumerable{T}"/> class.
    /// </summary>
    public static class CacheEnumerableExtensions
    {
        /// <summary>
        /// Caches the specified sequence and allow <paramref name="source"/> be enumerated only once. 
        /// Source sequence is advanced on result sequence advancing.
        /// </summary>
        /// <typeparam name="T">Type of element in sequence.</typeparam>
        /// <param name="source">The source enumerable.</param>
        /// <returns>Cached sequence.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="source"/> is null reference.</exception>
        public static IEnumerable<T> Cache<T>(this IEnumerable<T> source)
        {
            if (Object.ReferenceEquals(source, null))
                throw new ArgumentNullException("source");
            return new CacheEnumerable<T>(source);
        }
    }
}
